{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Linear Algebra\n",
    ":label:`sec_linear-algebra`\n",
    "\n",
    "\n",
    "Now that you can store and manipulate data,\n",
    "let us briefly review the subset of basic linear algebra\n",
    "that you will need to understand and implement\n",
    "most of models covered in this book.\n",
    "Below, we introduce the basic mathematical objects, arithmetic,\n",
    "and operations in linear algebra,\n",
    "expressing each of them through mathematical notation\n",
    "and the corresponding implementation in code.\n",
    "\n",
    "## Scalars\n",
    "\n",
    "If you never studied linear algebra or machine learning,\n",
    "then your past experience with math probably consisted\n",
    "of thinking about one number at a time.\n",
    "And, if you ever balanced a checkbook\n",
    "or even paid for dinner at a restaurant\n",
    "then you already know how to do basic things\n",
    "like adding and multiplying pairs of numbers.\n",
    "For example, the temperature in Palo Alto is $52$ degrees Fahrenheit.\n",
    "Formally, we call values consisting\n",
    "of just one numerical quantity *scalars*.\n",
    "If you wanted to convert this value to Celsius\n",
    "(the metric system's more sensible temperature scale),\n",
    "you would evaluate the expression $c = \\frac{5}{9}(f - 32)$, setting $f$ to $52$.\n",
    "In this equation, each of the terms---$5$, $9$, and $32$---are scalar values.\n",
    "The placeholders $c$ and $f$ are called *variables*\n",
    "and they represent unknown scalar values.\n",
    "\n",
    "In this book, we adopt the mathematical notation\n",
    "where scalar variables are denoted\n",
    "by ordinary lower-cased letters (e.g., $x$, $y$, and $z$).\n",
    "We denote the space of all (continuous) *real-valued* scalars by $\\mathbb{R}$.\n",
    "For expedience, we will punt on rigorous definitions\n",
    "of what precisely *space* is,\n",
    "but just remember for now that the expression $x \\in \\mathbb{R}$\n",
    "is a formal way to say that $x$ is a real-valued scalar.\n",
    "The symbol $\\in$ can be pronounced \"in\"\n",
    "and simply denotes membership in a set.\n",
    "Analogously, we could write $x, y \\in \\{0, 1\\}$\n",
    "to state that $x$ and $y$ are numbers\n",
    "whose value can only be $0$ or $1$.\n",
    "\n",
    "A scalar is represented by a NDArray with just one element.\n",
    "In the next snippet, we instantiate two scalars\n",
    "and perform some familiar arithmetic operations with them,\n",
    "namely addition, multiplication, division, and exponentiation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/\n",
    "%maven org.slf4j:slf4j-api:1.7.26\n",
    "%maven org.slf4j:slf4j-simple:1.7.26\n",
    "        \n",
    "%maven ai.djl:api:0.9.0\n",
    "%maven ai.djl:basicdataset:0.9.0\n",
    "\n",
    "// See https://github.com/awslabs/djl/blob/master/mxnet/mxnet-engine/README.md\n",
    "// MXNet \n",
    "%maven ai.djl.mxnet:mxnet-engine:0.9.0\n",
    "%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-backport"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.ndarray.*;\n",
    "NDManager manager = NDManager.newBaseManager();\n",
    "NDArray x = manager.create(3f);\n",
    "NDArray y = manager.create(2f);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.add(y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.mul(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.div(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.pow(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "## Vectors\n",
    "\n",
    "You can think of a vector as simply a list of scalar values.\n",
    "We call these values the *elements* (*entries* or *components*) of the vector.\n",
    "When our vectors represent examples from our dataset,\n",
    "their values hold some real-world significance.\n",
    "For example, if we were training a model to predict\n",
    "the risk that a loan defaults,\n",
    "we might associate each applicant with a vector\n",
    "whose components correspond to their income,\n",
    "length of employment, number of previous defaults, and other factors.\n",
    "If we were studying the risk of heart attacks hospital patients potentially face,\n",
    "we might represent each patient by a vector\n",
    "whose components capture their most recent vital signs,\n",
    "cholesterol levels, minutes of exercise per day, etc.\n",
    "In math notation, we will usually denote vectors as bold-faced,\n",
    "lower-cased letters (e.g., $\\mathbf{x}$, $\\mathbf{y}$, and $\\mathbf{z})$.\n",
    "\n",
    "We work with vectors via one-dimensional NDArrays.\n",
    "In general NDArrays can have arbitrary lengths,\n",
    "subject to the memory limits of your machine.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray x = manager.arange(4f);\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "We can refer to any element of a vector by using a subscript.\n",
    "For example, we can refer to the $i^\\mathrm{th}$ element of $\\mathbf{x}$ by $x_i$.\n",
    "Note that the element $x_i$ is a scalar,\n",
    "so we do not bold-face the font when referring to it.\n",
    "Extensive literature considers column vectors to be the default\n",
    "orientation of vectors, so does this book.\n",
    "In math, a vector $\\mathbf{x}$ can be written as\n",
    "\n",
    "$$\\mathbf{x} =\\begin{bmatrix}x_{1}  \\\\x_{2}  \\\\ \\vdots  \\\\x_{n}\\end{bmatrix},$$\n",
    ":eqlabel:`eq_vec_def`\n",
    "\n",
    "\n",
    "where $x_1, \\ldots, x_n$ are elements of the vector.\n",
    "In code, we access any element by indexing into the NDArray.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.get(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "### Length, Dimensionality, and Shape\n",
    "\n",
    "Let us revisit some concepts from :numref:`sec_ndarray`.\n",
    "A vector is just an array of numbers.\n",
    "And just as every array has a length, so does every vector.\n",
    "In math notation, if we want to say that a vector $\\mathbf{x}$\n",
    "consists of $n$ real-valued scalars,\n",
    "we can express this as $\\mathbf{x} \\in \\mathbb{R}^n$.\n",
    "The length of a vector is commonly called the *dimension* of the vector.\n",
    "\n",
    "As with an ordinary Java array, we can access the length. In the case of a NDArray we can achieve this by using the `size(0)` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.size(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "When a NDArray represents a vector (with precisely one axis),\n",
    "we can also access its length via the `getShape()` function.\n",
    "The shape lists the length (dimensionality)\n",
    "along each axis of the NDArray.\n",
    "For NDArrays with just one axis, the shape has just one element.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 20
   },
   "source": [
    "Note that the word \"dimension\" tends to get overloaded\n",
    "in these contexts and this tends to confuse people.\n",
    "To clarify, we use the dimensionality of a *vector* or an *axis*\n",
    "to refer to its length, i.e., the number of elements of a vector or an axis.\n",
    "However, we use the dimensionality of a NDArray\n",
    "to refer to the number of axes that a NDArray has.\n",
    "In this sense, the dimensionality of some axis of a NDArray\n",
    "will be the length of that axis.\n",
    "\n",
    "\n",
    "## Matrices\n",
    "\n",
    "Just as vectors generalize scalars from order zero to order one,\n",
    "matrices generalize vectors from order one to order two.\n",
    "Matrices, which we will typically denote with bold-faced, capital letters\n",
    "(e.g., $\\mathbf{X}$, $\\mathbf{Y}$, and $\\mathbf{Z}$),\n",
    "are represented in code as NDArray with two axes.\n",
    "\n",
    "In math notation, we use $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$\n",
    "to express that the matrix $\\mathbf{A}$ consists of $m$ rows and $n$ columns of real-valued scalars.\n",
    "Visually, we can illustrate any matrix $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$ as a table,\n",
    "where each element $a_{ij}$ belongs to the $i^{\\mathrm{th}}$ row and $j^{\\mathrm{th}}$ column:\n",
    "\n",
    "$$\\mathbf{A}=\\begin{bmatrix} a_{11} & a_{12} & \\cdots & a_{1n} \\\\ a_{21} & a_{22} & \\cdots & a_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ a_{m1} & a_{m2} & \\cdots & a_{mn} \\\\ \\end{bmatrix}.$$\n",
    ":eqlabel:`eq_matrix_def`\n",
    "\n",
    "\n",
    "For any $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$, the shape of $\\mathbf{A}$\n",
    "is ($m$, $n$) or $m \\times n$.\n",
    "Specifically, when a matrix has the same number of rows and columns,\n",
    "its shape becomes a square; thus, it is called a *square matrix*.\n",
    "\n",
    "We can create an $m \\times n$ matrix\n",
    "by specifying a shape with two components $m$ and $n$\n",
    "when calling any of our favorite functions for instantiating a NDArray.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray A = manager.arange(20f).reshape(5,4);\n",
    "A"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 24
   },
   "source": [
    "We can access the scalar element $a_{ij}$ of a matrix $\\mathbf{A}$ in :eqref:`eq_matrix_def`\n",
    "by specifying the indices for the row ($i$) and column ($j$),\n",
    "such as $[\\mathbf{A}]_{ij}$.\n",
    "When the scalar elements of a matrix $\\mathbf{A}$, such as in :eqref:`eq_matrix_def`, are not given,\n",
    "we may simply use the lower-case letter of the matrix $\\mathbf{A}$ with the index subscript, $a_{ij}$,\n",
    "to refer to $[\\mathbf{A}]_{ij}$.\n",
    "To keep notation simple, commas are inserted to separate indices only when necessary,\n",
    "such as $a_{2, 3j}$ and $[\\mathbf{A}]_{2i-1, 3}$.\n",
    "\n",
    "\n",
    "Sometimes, we want to flip the axes.\n",
    "When we exchange a matrix's rows and columns,\n",
    "the result is called the *transpose* of the matrix.\n",
    "Formally, we signify a matrix $\\mathbf{A}$'s transpose by $\\mathbf{A}^\\top$\n",
    "and if $\\mathbf{B} = \\mathbf{A}^\\top$, then $b_{ij} = a_{ji}$ for any $i$ and $j$.\n",
    "Thus, the transpose of $\\mathbf{A}$ in :eqref:`eq_matrix_def` is\n",
    "a $n \\times m$ matrix:\n",
    "\n",
    "$$\n",
    "\\mathbf{A}^\\top =\n",
    "\\begin{bmatrix}\n",
    "    a_{11} & a_{21} & \\dots  & a_{m1} \\\\\n",
    "    a_{12} & a_{22} & \\dots  & a_{m2} \\\\\n",
    "    \\vdots & \\vdots & \\ddots  & \\vdots \\\\\n",
    "    a_{1n} & a_{2n} & \\dots  & a_{mn}\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "Now we access a matrix's transpose in code.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.transpose()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 28
   },
   "source": [
    "As a special type of the square matrix,\n",
    "a *symmetric matrix* $\\mathbf{A}$ is equal to its transpose:\n",
    "$\\mathbf{A} = \\mathbf{A}^\\top$.\n",
    "Here we define a symmetric matrix `B`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray B = manager.create(new float[][] {{1, 2, 3}, {2, 0, 4}, {3, 4, 5}});\n",
    "B"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "Now we compare `B` with its transpose.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "B.eq(B.transpose())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36
   },
   "source": [
    "Matrices are useful data structures:\n",
    "they allow us to organize data that have different modalities of variation.\n",
    "For example, rows in our matrix might correspond to different houses (data examples),\n",
    "while columns might correspond to different attributes.\n",
    "This should sound familiar if you have ever used spreadsheet software or\n",
    "have read :numref:`sec_tablesaw`.\n",
    "Thus, although the default orientation of a single vector is a column vector,\n",
    "in a matrix that represents a tabular dataset,\n",
    "it is more conventional to treat each data example as a row vector in the matrix.\n",
    "And, as we will see in later chapters,\n",
    "this convention will enable common deep learning practices.\n",
    "For example, along the outermost axis of a NDArray,\n",
    "we can access or enumerate minibatches of data examples,\n",
    "or just data examples if no minibatch exists.\n",
    "\n",
    "\n",
    "## NDArrays\n",
    "\n",
    "Just as vectors generalize scalars, and matrices generalize vectors, we can build data structures with even more axes. NDArrays (\"NDArrays\" in this subsection refer to algebraic objects) give us a generic way of describing $n$-dimensional arrays with an arbitrary number of axes. Vectors, for example, are first-order NDArrays, and matrices are second-order NDArrays.\n",
    "NDArrays are denoted with capital letters of a special font face\n",
    "(e.g., $\\mathsf{X}$, $\\mathsf{Y}$, and $\\mathsf{Z}$)\n",
    "and their indexing mechanism (e.g., $x_{ijk}$ and $[\\mathsf{X}]_{1, 2i-1, 3}$) is similar to that of matrices.\n",
    "\n",
    "NDArrays will become more important when we start working with images, which arrive as $n$-dimensional arrays with 3 axes corresponding to the height, width, and a *channel* axis for stacking the color channels (red, green, and blue). For now, we will skip over higher order NDArrays and focus on the basics.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray X = manager.arange(24f).reshape(2, 3, 4);\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "## Basic Properties of NDArray Arithmetic\n",
    "\n",
    "Scalars, vectors, matrices, and NDArrays (\"NDArrays\" in this subsection refer to algebraic objects)\n",
    "of an arbitrary number of axes\n",
    "have some nice properties that often come in handy.\n",
    "For example, you might have noticed\n",
    "from the definition of an elementwise operation\n",
    "that any elementwise unary operation does not change the shape of its operand.\n",
    "Similarly, given any two NDArrays with the same shape,\n",
    "the result of any binary elementwise operation\n",
    "will be a NDArray of that same shape.\n",
    "For example, adding two matrices of the same shape\n",
    "performs elementwise addition over these two matrices.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray A = manager.arange(20f).reshape(5,4);\n",
    "NDArray B = A.duplicate(); // Assign a copy of `A` to `B` by allocating new memory\n",
    "A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "A.add(B)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 44
   },
   "source": [
    "Specifically, elementwise multiplication of two matrices is called their *Hadamard product* (math notation $\\odot$).\n",
    "Consider matrix $\\mathbf{B} \\in \\mathbb{R}^{m \\times n}$ whose element of row $i$ and column $j$ is $b_{ij}$. The Hadamard product of matrices $\\mathbf{A}$ (defined in :eqref:`eq_matrix_def`) and $\\mathbf{B}$\n",
    "\n",
    "$$\n",
    "\\mathbf{A} \\odot \\mathbf{B} =\n",
    "\\begin{bmatrix}\n",
    "    a_{11}  b_{11} & a_{12}  b_{12} & \\dots  & a_{1n}  b_{1n} \\\\\n",
    "    a_{21}  b_{21} & a_{22}  b_{22} & \\dots  & a_{2n}  b_{2n} \\\\\n",
    "    \\vdots & \\vdots & \\ddots & \\vdots \\\\\n",
    "    a_{m1}  b_{m1} & a_{m2}  b_{m2} & \\dots  & a_{mn}  b_{mn}\n",
    "\\end{bmatrix}.\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.mul(B);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 48
   },
   "source": [
    "Multiplying or adding a NDArray by a scalar also does not change the shape of the NDArray,\n",
    "where each element of the operand NDArray will be added or multiplied by the scalar.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int a = 2;\n",
    "NDArray X = manager.arange(24f).reshape(2, 3, 4);\n",
    "X.add(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(X.mul(a)).getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "## Reduction\n",
    ":label:`subseq_lin-alg-reduction`\n",
    "\n",
    "One useful operation that we can perform with arbitrary NDArrays\n",
    "is to calculate the sum of their elements.\n",
    "In mathematical notation, we express sums using the $\\sum$ symbol.\n",
    "To express the sum of the elements in a vector $\\mathbf{x}$ of length $d$,\n",
    "we write $\\sum_{i=1}^d x_i$.\n",
    "In code, we can just call the function for calculating the sum.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray x = manager.arange(4f);\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 56
   },
   "source": [
    "We can express sums over the elements of NDArrays of arbitrary shape.\n",
    "For example, the sum of the elements of an $m \\times n$ matrix $\\mathbf{A}$ could be written $\\sum_{i=1}^{m} \\sum_{j=1}^{n} a_{ij}$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.getShape()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, invoking the function for calculating the sum\n",
    "*reduces* a NDArray along all its axes to a scalar.\n",
    "We can also specify the axes along which the NDArray is reduced via summation.\n",
    "Take matrices as an example.\n",
    "To reduce the row dimension (axis 0) by summing up elements of all the rows,\n",
    "we specify `new int[] {0}` when invoking the function.\n",
    "Since the input matrix reduces along axis 0 to generate the output vector,\n",
    "the dimension of axis 0 of the input is lost in the output shape.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray ASumAxis0 = A.sum(new int[] {0});\n",
    "ASumAxis0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ASumAxis0.getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 64
   },
   "source": [
    "Specifying `new int[] {1}` will reduce the column dimension (axis 1) by summing up elements of all the columns.\n",
    "Thus, the dimension of axis 1 of the input is lost in the output shape.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray ASumAxis1 = A.sum(new int[] {1});\n",
    "ASumAxis1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ASumAxis1.getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 68
   },
   "source": [
    "Reducing a matrix along both rows and columns via summation\n",
    "is equivalent to summing up all the elements of the matrix.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.sum(new int[] {0,1}) // Same as `A.sum()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 72
   },
   "source": [
    "A related quantity is the *mean*, which is also called the *average*.\n",
    "We calculate the mean by dividing the sum by the total number of elements.\n",
    "In code, we could just call the function for calculating the mean\n",
    "on NDArrays of arbitrary shape.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.sum().div(A.size())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 76
   },
   "source": [
    "Likewise, the function for calculating the mean can also reduce a NDArray along the specified axes.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.mean(new int[] {0})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.sum(new int[] {0}).div(A.getShape().get(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 80
   },
   "source": [
    "### Non-Reduction Sum\n",
    ":label:`subseq_lin-alg-non-reduction`\n",
    "\n",
    "However, sometimes it can be useful to keep the number of axes unchanged\n",
    "when invoking the function for calculating the sum or mean.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray sumA = A.sum(new int[] {1}, true);\n",
    "sumA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 84
   },
   "source": [
    "For instance, since `sumA` still keeps its two axes after summing each row, we can divide `A` by `sumA` with broadcasting.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.div(sumA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 88
   },
   "source": [
    "If we want to calculate the cumulative sum of elements of `A` along some axis, say axis 0 (row by row),\n",
    "we can call the `cumsum` function. This function will not reduce the input NDArray along any axis.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.cumSum(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 92
   },
   "source": [
    "## Dot Products\n",
    "\n",
    "So far, we have only performed elementwise operations, sums, and averages. And if this was all we could do, linear algebra probably would not deserve its own section. However, one of the most fundamental operations is the dot product. Given two vectors $\\mathbf{x}, \\mathbf{y} \\in \\mathbb{R}^d$, their *dot product* $\\mathbf{x}^\\top \\mathbf{y}$ (or $\\langle \\mathbf{x}, \\mathbf{y}  \\rangle$) is a sum over the products of the elements at the same position: $\\mathbf{x}^\\top \\mathbf{y} = \\sum_{i=1}^{d} x_i y_i$.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.ndarray.types.*;\n",
    "\n",
    "NDArray y = manager.ones(new Shape(4));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.dot(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 96
   },
   "source": [
    "Note that we can express the dot product of two vectors equivalently by performing an elementwise multiplication and then a sum:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.mul(y).sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 100
   },
   "source": [
    "Dot products are useful in a wide range of contexts.\n",
    "For example, given some set of values,\n",
    "denoted by a vector $\\mathbf{x}  \\in \\mathbb{R}^d$\n",
    "and a set of weights denoted by $\\mathbf{w} \\in \\mathbb{R}^d$,\n",
    "the weighted sum of the values in $\\mathbf{x}$\n",
    "according to the weights $\\mathbf{w}$\n",
    "could be expressed as the dot product $\\mathbf{x}^\\top \\mathbf{w}$.\n",
    "When the weights are non-negative\n",
    "and sum to one (i.e., $\\left(\\sum_{i=1}^{d} {w_i} = 1\\right)$),\n",
    "the dot product expresses a *weighted average*.\n",
    "After normalizing two vectors to have the unit length,\n",
    "the dot products express the cosine of the angle between them.\n",
    "We will formally introduce this notion of *length* later in this section.\n",
    "\n",
    "\n",
    "## Matrix-Vector Products\n",
    "\n",
    "Now that we know how to calculate dot products,\n",
    "we can begin to understand *matrix-vector products*.\n",
    "Recall the matrix $\\mathbf{A} \\in \\mathbb{R}^{m \\times n}$\n",
    "and the vector $\\mathbf{x} \\in \\mathbb{R}^n$\n",
    "defined and visualized in :eqref:`eq_matrix_def` and :eqref:`eq_vec_def` respectively.\n",
    "Let us start off by visualizing the matrix $\\mathbf{A}$ in terms of its row vectors\n",
    "\n",
    "$$\\mathbf{A}=\n",
    "\\begin{bmatrix}\n",
    "\\mathbf{a}^\\top_{1} \\\\\n",
    "\\mathbf{a}^\\top_{2} \\\\\n",
    "\\vdots \\\\\n",
    "\\mathbf{a}^\\top_m \\\\\n",
    "\\end{bmatrix},$$\n",
    "\n",
    "where each $\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^n$\n",
    "is a row vector representing the $i^\\mathrm{th}$ row of the matrix $\\mathbf{A}$.\n",
    "The matrix-vector product $\\mathbf{A}\\mathbf{x}$\n",
    "is simply a column vector of length $m$,\n",
    "whose $i^\\mathrm{th}$ element is the dot product $\\mathbf{a}^\\top_i \\mathbf{x}$:\n",
    "\n",
    "$$\n",
    "\\mathbf{A}\\mathbf{x}\n",
    "= \\begin{bmatrix}\n",
    "\\mathbf{a}^\\top_{1} \\\\\n",
    "\\mathbf{a}^\\top_{2} \\\\\n",
    "\\vdots \\\\\n",
    "\\mathbf{a}^\\top_m \\\\\n",
    "\\end{bmatrix}\\mathbf{x}\n",
    "= \\begin{bmatrix}\n",
    " \\mathbf{a}^\\top_{1} \\mathbf{x}  \\\\\n",
    " \\mathbf{a}^\\top_{2} \\mathbf{x} \\\\\n",
    "\\vdots\\\\\n",
    " \\mathbf{a}^\\top_{m} \\mathbf{x}\\\\\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "We can think of multiplication by a matrix $\\mathbf{A}\\in \\mathbb{R}^{m \\times n}$\n",
    "as a transformation that projects vectors\n",
    "from $\\mathbb{R}^{n}$ to $\\mathbb{R}^{m}$.\n",
    "These transformations turn out to be remarkably useful.\n",
    "For example, we can represent rotations\n",
    "as multiplications by a square matrix.\n",
    "As we will see in subsequent chapters,\n",
    "we can also use matrix-vector products\n",
    "to describe the most intensive calculations\n",
    "required when computing each layer in a neural network\n",
    "given the values of the previous layer.\n",
    "\n",
    "Expressing matrix-vector products in code with NDArrays,\n",
    "we use the same `dot` function as for dot products.\n",
    "When we call `A.dot(x)` with a matrix `A` and a vector `x`,\n",
    "the matrix-vector product is performed.\n",
    "Note that the column dimension of `A` (its length along axis 1)\n",
    "must be the same as the dimension of `x` (its length).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.getShape()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x.getShape()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A.dot(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 104
   },
   "source": [
    "## Matrix-Matrix Multiplication\n",
    "\n",
    "If you have gotten the hang of dot products and matrix-vector products,\n",
    "then *matrix-matrix multiplication* should be straightforward.\n",
    "\n",
    "Say that we have two matrices $\\mathbf{A} \\in \\mathbb{R}^{n \\times k}$ and $\\mathbf{B} \\in \\mathbb{R}^{k \\times m}$:\n",
    "\n",
    "$$\\mathbf{A}=\\begin{bmatrix}\n",
    " a_{11} & a_{12} & \\cdots & a_{1k} \\\\\n",
    " a_{21} & a_{22} & \\cdots & a_{2k} \\\\\n",
    "\\vdots & \\vdots & \\ddots & \\vdots \\\\\n",
    " a_{n1} & a_{n2} & \\cdots & a_{nk} \\\\\n",
    "\\end{bmatrix},\\quad\n",
    "\\mathbf{B}=\\begin{bmatrix}\n",
    " b_{11} & b_{12} & \\cdots & b_{1m} \\\\\n",
    " b_{21} & b_{22} & \\cdots & b_{2m} \\\\\n",
    "\\vdots & \\vdots & \\ddots & \\vdots \\\\\n",
    " b_{k1} & b_{k2} & \\cdots & b_{km} \\\\\n",
    "\\end{bmatrix}.$$\n",
    "\n",
    "\n",
    "Denote by $\\mathbf{a}^\\top_{i} \\in \\mathbb{R}^k$\n",
    "the row vector representing the $i^\\mathrm{th}$ row of the matrix $\\mathbf{A}$,\n",
    "and let $\\mathbf{b}_{j} \\in \\mathbb{R}^k$\n",
    "be the column vector from the $j^\\mathrm{th}$ column of the matrix $\\mathbf{B}$.\n",
    "To produce the matrix product $\\mathbf{C} = \\mathbf{A}\\mathbf{B}$, it is easiest to think of $\\mathbf{A}$ in terms of its row vectors and $\\mathbf{B}$ in terms of its column vectors:\n",
    "\n",
    "$$\\mathbf{A}=\n",
    "\\begin{bmatrix}\n",
    "\\mathbf{a}^\\top_{1} \\\\\n",
    "\\mathbf{a}^\\top_{2} \\\\\n",
    "\\vdots \\\\\n",
    "\\mathbf{a}^\\top_n \\\\\n",
    "\\end{bmatrix},\n",
    "\\quad \\mathbf{B}=\\begin{bmatrix}\n",
    " \\mathbf{b}_{1} & \\mathbf{b}_{2} & \\cdots & \\mathbf{b}_{m} \\\\\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "\n",
    "Then the matrix product $\\mathbf{C} \\in \\mathbb{R}^{n \\times m}$ is produced as we simply compute each element $c_{ij}$ as the dot product $\\mathbf{a}^\\top_i \\mathbf{b}_j$:\n",
    "\n",
    "$$\\mathbf{C} = \\mathbf{AB} = \\begin{bmatrix}\n",
    "\\mathbf{a}^\\top_{1} \\\\\n",
    "\\mathbf{a}^\\top_{2} \\\\\n",
    "\\vdots \\\\\n",
    "\\mathbf{a}^\\top_n \\\\\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    " \\mathbf{b}_{1} & \\mathbf{b}_{2} & \\cdots & \\mathbf{b}_{m} \\\\\n",
    "\\end{bmatrix}\n",
    "= \\begin{bmatrix}\n",
    "\\mathbf{a}^\\top_{1} \\mathbf{b}_1 & \\mathbf{a}^\\top_{1}\\mathbf{b}_2& \\cdots & \\mathbf{a}^\\top_{1} \\mathbf{b}_m \\\\\n",
    " \\mathbf{a}^\\top_{2}\\mathbf{b}_1 & \\mathbf{a}^\\top_{2} \\mathbf{b}_2 & \\cdots & \\mathbf{a}^\\top_{2} \\mathbf{b}_m \\\\\n",
    " \\vdots & \\vdots & \\ddots &\\vdots\\\\\n",
    "\\mathbf{a}^\\top_{n} \\mathbf{b}_1 & \\mathbf{a}^\\top_{n}\\mathbf{b}_2& \\cdots& \\mathbf{a}^\\top_{n} \\mathbf{b}_m\n",
    "\\end{bmatrix}.\n",
    "$$\n",
    "\n",
    "We can think of the matrix-matrix multiplication $\\mathbf{AB}$ as simply performing $m$ matrix-vector products and stitching the results together to form an $n \\times m$ matrix.\n",
    "In the following snippet, we perform matrix multiplication on `A` and `B`.\n",
    "Here, `A` is a matrix with 5 rows and 4 columns,\n",
    "and `B` is a matrix with 4 rows and 3 columns.\n",
    "After multiplication, we obtain a matrix with 5 rows and 3 columns.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray B = manager.ones(new Shape(4,3));\n",
    "A.dot(B)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 108
   },
   "source": [
    "Matrix-matrix multiplication can be simply called *matrix multiplication*, and should not be confused with the Hadamard product.\n",
    "\n",
    "\n",
    "## Norms\n",
    ":label:`subsec_lin-algebra-norms`\n",
    "\n",
    "Some of the most useful operators in linear algebra are *norms*.\n",
    "Informally, the norm of a vector tells us how *big* a vector is.\n",
    "The notion of *size* under consideration here\n",
    "concerns not dimensionality\n",
    "but rather the magnitude of the components.\n",
    "\n",
    "In linear algebra, a vector norm is a function $f$ that maps a vector\n",
    "to a scalar, satisfying a handful of properties.\n",
    "Given any vector $\\mathbf{x}$,\n",
    "the first property says\n",
    "that if we scale all the elements of a vector\n",
    "by a constant factor $\\alpha$,\n",
    "its norm also scales by the *absolute value*\n",
    "of the same constant factor:\n",
    "\n",
    "$$f(\\alpha \\mathbf{x}) = |\\alpha| f(\\mathbf{x}).$$\n",
    "\n",
    "\n",
    "The second property is the familiar triangle inequality:\n",
    "\n",
    "$$f(\\mathbf{x} + \\mathbf{y}) \\leq f(\\mathbf{x}) + f(\\mathbf{y}).$$\n",
    "\n",
    "\n",
    "The third property simply says that the norm must be non-negative:\n",
    "\n",
    "$$f(\\mathbf{x}) \\geq 0.$$\n",
    "\n",
    "That makes sense, as in most contexts the smallest *size* for anything is 0.\n",
    "The final property requires that the smallest norm is achieved and only achieved\n",
    "by a vector consisting of all zeros.\n",
    "\n",
    "$$\\forall i, [\\mathbf{x}]_i = 0 \\Leftrightarrow f(\\mathbf{x})=0.$$\n",
    "\n",
    "You might notice that norms sound a lot like measures of distance.\n",
    "And if you remember Euclidean distances\n",
    "(think Pythagoras' theorem) from grade school,\n",
    "then the concepts of non-negativity and the triangle inequality might ring a bell.\n",
    "In fact, the Euclidean distance is a norm:\n",
    "specifically it is the $L_2$ norm.\n",
    "Suppose that the elements in the $n$-dimensional vector\n",
    "$\\mathbf{x}$ are $x_1, \\ldots, x_n$.\n",
    "The $L_2$ *norm* of $\\mathbf{x}$ is the square root of the sum of the squares of the vector elements:\n",
    "\n",
    "$$\\|\\mathbf{x}\\|_2 = \\sqrt{\\sum_{i=1}^n x_i^2},$$\n",
    "\n",
    "where the subscript $2$ is often omitted in $L_2$ norms, i.e., $\\|\\mathbf{x}\\|$ is equivalent to $\\|\\mathbf{x}\\|_2$. In code, we can calculate the $L_2$ norm of a vector as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public NDArray l2Norm(NDArray w){\n",
    "    return ((w.pow(2)).sum()).sqrt();\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray u = manager.create(new float[] {3,-4});\n",
    "l2Norm(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 112
   },
   "source": [
    "In deep learning, we work more often\n",
    "with the squared $L_2$ norm.\n",
    "You will also frequently encounter the $L_1$ *norm*,\n",
    "which is expressed as the sum of the absolute values of the vector elements:\n",
    "\n",
    "$$\\|\\mathbf{x}\\|_1 = \\sum_{i=1}^n \\left|x_i \\right|.$$\n",
    "\n",
    "As compared with the $L_2$ norm,\n",
    "it is less influenced by outliers.\n",
    "To calculate the $L_1$ norm, we compose\n",
    "the absolute value function with a sum over the elements.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "u.abs().sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 116
   },
   "source": [
    "Both the $L_2$ norm and the $L_1$ norm\n",
    "are special cases of the more general $L_p$ *norm*:\n",
    "\n",
    "$$\\|\\mathbf{x}\\|_p = \\left(\\sum_{i=1}^n \\left|x_i \\right|^p \\right)^{1/p}.$$\n",
    "\n",
    "Analogous to $L_2$ norms of vectors,\n",
    "the *Frobenius norm* of a matrix $\\mathbf{X} \\in \\mathbb{R}^{m \\times n}$\n",
    "is the square root of the sum of the squares of the matrix elements:\n",
    "\n",
    "$$\\|\\mathbf{X}\\|_F = \\sqrt{\\sum_{i=1}^m \\sum_{j=1}^n x_{ij}^2}.$$\n",
    "\n",
    "The Frobenius norm satisfies all the properties of vector norms.\n",
    "It behaves as if it were an $L_2$ norm of a matrix-shaped vector.\n",
    "Invoking the following function will calculate the Frobenius norm of a matrix.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2Norm(manager.ones(new Shape(4,9)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 120
   },
   "source": [
    "### Norms and Objectives\n",
    ":label:`subsec_norms_and_objectives`\n",
    "\n",
    "While we do not want to get too far ahead of ourselves,\n",
    "we can plant some intuition already about why these concepts are useful.\n",
    "In deep learning, we are often trying to solve optimization problems:\n",
    "*maximize* the probability assigned to observed data;\n",
    "*minimize* the distance between predictions\n",
    "and the ground-truth observations.\n",
    "Assign vector representations to items (like words, products, or news articles)\n",
    "such that the distance between similar items is minimized,\n",
    "and the distance between dissimilar items is maximized.\n",
    "Oftentimes, the objectives, perhaps the most important components\n",
    "of deep learning algorithms (besides the data),\n",
    "are expressed as norms.\n",
    "\n",
    "\n",
    "\n",
    "## More on Linear Algebra\n",
    "\n",
    "In just this section,\n",
    "we have taught you all the linear algebra\n",
    "that you will need to understand\n",
    "a remarkable chunk of modern deep learning.\n",
    "There is a lot more to linear algebra\n",
    "and a lot of that mathematics is useful for machine learning.\n",
    "For example, matrices can be decomposed into factors,\n",
    "and these decompositions can reveal\n",
    "low-dimensional structure in real-world datasets.\n",
    "There are entire subfields of machine learning\n",
    "that focus on using matrix decompositions\n",
    "and their generalizations to high-order NDArrays\n",
    "to discover structure in datasets and solve prediction problems.\n",
    "But this book focuses on deep learning.\n",
    "And we believe you will be much more inclined to learn more mathematics\n",
    "once you have gotten your hands dirty\n",
    "deploying useful machine learning models on real datasets.\n",
    "So while we reserve the right to introduce more mathematics much later on,\n",
    "we will wrap up this section here.\n",
    "\n",
    "If you are eager to learn more about linear algebra,\n",
    "you may refer to either the\n",
    "[online appendix on linear algebraic operations](https://d2l.ai/chapter_appendix-mathematics-for-deep-learning/geometry-linear-algebraic-ops.html)\n",
    "or other excellent resources :cite:`Strang.1993,Kolter.2008,Petersen.Pedersen.ea.2008`.\n",
    "\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "* Scalars, vectors, matrices, and NDArrays are basic mathematical objects in linear algebra.\n",
    "* Vectors generalize scalars, and matrices generalize vectors.\n",
    "* Scalars, vectors, matrices, and NDArrays have zero, one, two, and an arbitrary number of axes, respectively.\n",
    "* A NDArray can be reduced along the specified axes by `sum` and `mean`.\n",
    "* Elementwise multiplication of two matrices is called their Hadamard product. It is different from matrix multiplication.\n",
    "* In deep learning, we often work with norms such as the $L_1$ norm, the $L_2$ norm, and the Frobenius norm.\n",
    "* We can perform a variety of operations over scalars, vectors, matrices, and NDArrays.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Prove that the transpose of a matrix $\\mathbf{A}$'s transpose is $\\mathbf{A}$: $(\\mathbf{A}^\\top)^\\top = \\mathbf{A}$.\n",
    "1. Given two matrices $\\mathbf{A}$ and $\\mathbf{B}$, show that the sum of transposes is equal to the transpose of a sum: $\\mathbf{A}^\\top + \\mathbf{B}^\\top = (\\mathbf{A} + \\mathbf{B})^\\top$.\n",
    "1. Given any square matrix $\\mathbf{A}$, is $\\mathbf{A} + \\mathbf{A}^\\top$ always symmetric? Why?\n",
    "1. We defined the NDArray `X` of shape (2, 3, 4) in this section. What is the output of `X.size()`?\n",
    "1. For a NDArray `X` of arbitrary shape, does `X.size()` always correspond to the length of a certain axis of `X`? What is that axis?\n",
    "1. Run `A.div(A.sum(new int[] {1}))` and see what happens. Can you analyze the reason?\n",
    "1. When traveling between two points in Manhattan, what is the distance that you need to cover in terms of the coordinates, i.e., in terms of avenues and streets? Can you travel diagonally?\n",
    "1. Consider a NDArray with shape (2, 3, 4). What are the shapes of the summation outputs along axis 0, 1, and 2?\n",
    "1. Feed a NDArray with 3 or more axes to the `l2Norm` function and observe its output. What does this function compute for NDArrays of arbitrary shape?\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "11.0.9.1+1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
